<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { onMounted, ref, watch } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

// 导入echarts以解决全局变量问题
import * as echarts from 'echarts';

interface MileageData {
  licensePlate: string;
  mileage: number;
}

const props = defineProps<{
  data: MileageData[];
}>();

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);

// 监听数据变化，重新渲染图表
watch(
  () => props.data,
  () => {
    renderChart();
  },
  { deep: true },
);

const renderChart = () => {
  if (!props.data || props.data.length === 0) return;

  renderEcharts({
    grid: {
      bottom: 60,
      left: 80,
      right: 20,
      top: 20,
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
      axisLabel: {
        formatter: '{value} 公里',
      },
    },
    yAxis: {
      type: 'category',
      data: props.data.map((item) => item.licensePlate),
      axisLabel: {
        interval: 0,
        rotate: 0,
      },
    },
    series: [
      {
        name: '行驶里程',
        type: 'bar',
        data: props.data.map((item) => ({
          value: item.mileage,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#5ab1ef' },
              { offset: 1, color: '#019680' },
            ]),
          },
        })),
        label: {
          show: true,
          position: 'right',
          formatter: '{c} 公里',
        },
      },
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter: (params: any) => {
        const data = params[0];
        return `
          <div style="padding: 8px;">
            <div style="font-weight: bold; margin-bottom: 4px;">${data.name}</div>
            <div>行驶里程: <span style="color: #5ab1ef;">${data.value} 公里</span></div>
          </div>
        `;
      },
    },
    animation: true,
  });
};

onMounted(() => {
  renderChart();
});
</script>

<template>
  <div class="h-full w-full">
    <EchartsUI ref="chartRef" />
  </div>
</template>

<style scoped>
/* 图表容器样式 */
.w-full {
  width: 100%;
}

.h-full {
  height: 100%;
}
</style>
